/**
* @description: Login
* @author: 王有余
* @date: 2021-09-23 14:51:28
*/


<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router'
import { useCounterStore } from './../stores/counter'
import { NFlex, NCard, NInput, NButton, NTabs, NTabPane } from 'naive-ui';
import { LOG_IN, LOG_FACE } from "@/service/apis/apis";
import { createDiscreteApi } from 'naive-ui'
import { getJmg, encrypt} from '@/service/jmg';
import  { WxLogin } from '@/assets/utils/wxLogin'
import unifiedLogin from '@/service/login';

const { message } = createDiscreteApi(["message"])
/**
 * 对于登陆成功的用户，修改pinia的state中的isLogin为true
 * 对于登陆失败的用户，提示错误信息
 * 对于未登录的用户，跳转到登录页面
 * 对于已登录的用户，跳转到主页
 * 对于未知的错误，提示错误信息
 */
const counterStore = useCounterStore()

const username = ref('001995');
const password = ref('12345678Qq');
const router = useRouter()
const jmg = ref()
const secret = ref('')
const videoRef = ref()
const canvasRef = ref()
const streams = ref()
const myConstraints = ref({
    video: {
        facingMode: "user", // 优先调用前置摄像头
    },
})
const base64 = ref()

onMounted(() => {
    if (counterStore.isLogin) {
        console.log('重复渲染登录页')
        return
    }
    getJmg((reslut:any) => {
        if(reslut.error){
            message.error("本地加密狗启动失败！")
        }else{
            message.success("本地加密狗启动成功！")
            jmg.value = reslut.jmg
            secret.value = reslut.secret
        }
    })
})
onUnmounted(() => {
    handleUpdateValue('close')
})
const pfocus = ref()
const passfocus = () => {
    pfocus.value.focus()
}

const login = () => {
    let p = {
        username: username.value,
        encryptedPassword: encrypt(password.value, secret.value),
        jmg: jmg.value
    }
    unifiedLogin(router, p, LOG_IN, {})
}


const handleUpdateValue = (value: string) => {
    if (value == 'renlian') {
        videoOpen()
    } else {
        videoClose()
    }
    if (value == 'weixin') {
        const saltValue = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
        // https://developers.weixin.qq.com/doc/oplatform/Website_App/WeChat_Login/Wechat_Login.html
        setTimeout(() => {
            const i = new WxLogin({
                // self_redirect: true,
                id: "wechatQrImgIframe",
                appid: "wx61163b02c125c40e",
                scope: "snsapi_login",
                redirect_uri: import.meta.env.VITE_WX_REDIRECT_URI,
                stylelite: 1,
                state: saltValue
            });
        }, 100);
    }
}

const videoOpen = () => {
    navigator.mediaDevices.getUserMedia(myConstraints.value).then(
        (stream) => {
            streams.value = stream
            videoRef.value.srcObject = stream;
            //播放视频
            videoRef.value.play();
            // 关闭摄像

        },
        (error) => {
            console.error(error.name || error);
        }
    );
};

const videoClose = () => {
    if (streams.value) {
        streams.value.getTracks().forEach((track: any) => track.stop());
    }
};

const handleShoot = () => {
    let canvas = document.createElement("canvas");
    canvas.width = 600 * 0.9; // 不知道为什么有拉伸，所以乘以0.9
    canvas.height = 400;
    const context = canvas.getContext("2d");
    context?.drawImage(videoRef.value, 0, 0, canvas.width, canvas.height);
    base64.value = canvas.toDataURL("image/png", 0.1);
    unifiedLogin(router, { img: base64.value, jmg: jmg.value }, LOG_FACE, {})
}
</script>
<template>
    <NFlex justify="space-between" style=" border: 0px solid #ff1111; width: 100vw;height: 100vh;">
        <n-flex style="border: 0px solid #ff1111;">
            <div></div>
        </n-flex>
        <n-flex vertical justify="center" style="border: 0px solid #ff1111;">

            <n-card title="山东发达AI数字化智慧平台" style="width: calc(100vw / 4);height: calc(100vh / 2);">
                <n-tabs default-value="zhanghao" type="line" animated justify-content="space-evenly" trigger="click"
                    @update:value="handleUpdateValue">
                    <n-tab-pane name="weixin" tab="微信登录">
                        <div id="wechatQrImgIframe" style="text-align: center; margin-top: 50px"></div>
                    </n-tab-pane>
                    <n-tab-pane name="renlian" tab="人脸登录">
                        <div class="rl_video">
                            <div class="rl_video_ladding">
                                <img src="../assets/image/face_frame.png" class="face_img" ></img>
                                <video ref="videoRef" class="rl_video_ladding_video"></video>
                            </div>
                            <!-- <div class="" style="text-align: center;">
                                请检查设备!!!style="display: none"
                            </div> -->
                        </div>
                        <!-- <canvas ref="canvasRef"></canvas> -->
                        <n-button type="primary" attr-type="button" @click="handleShoot"
                            style="margin-left: 183px;">拍照登录</n-button>

                    </n-tab-pane>
                    <n-tab-pane name="zhanghao" tab="账号登录">
                        <n-input v-model:value="username" placeholder="请输入手机号/工号" style="margin-bottom: 10px;"
                            type="text" maxlength="11" show-count clearable @keydown.enter.native="passfocus" />
                        <n-input ref="pfocus" v-model:value="password" type="password" placeholder="请输入密码"
                            maxlength="16" show-count style="margin-bottom: 10px;" clearable
                            @keydown.enter.native="login" />
                        <n-button type="primary" @click="login" style="margin-left: 183px;">登录</n-button>
                    </n-tab-pane>
                </n-tabs>
            </n-card>

        </n-flex>
        <n-flex style="border: 0px solid #eee;">
            <div> </div>
        </n-flex>
    </NFlex>
</template>
<style scoped>
.rl_video {
    /* width: 400px; */
    height: 270px;
    border-radius: 50%;
    /*background-color: rgb(38, 57, 57);*/
    position: relative;
}

.rl_video_ladding {
    width: 260px;
    height: 260px;
    border-radius: 50%;
    background-color: rgb(38, 57, 57);
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background: white;
    animation: changeBg 5s infinite;
    position: relative;
}

.rl_video_ladding_video {
    width: 250px;
    height: 250px;
    border-radius: 50%;
    object-fit: cover;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}
.face_img {
    width: 250px;
    height: 250px;
    border-radius: 50%;
    left: 2%;
    top: 2%;
    position: absolute;
    z-index: 100;
}
</style>